package com.sunnyweather.android.ui.weather

import androidx.lifecycle.*
import com.sunnyweather.android.logic.Repository
import com.sunnyweather.android.logic.model.Location
import com.sunnyweather.android.logic.model.Place
import com.sunnyweather.android.logic.model.Weather
import com.sunnyweather.android.logic.util.LogUtil

class WeatherViewModel :ViewModel(){
    //UI层返回的位置信息
    private val locationLiveData=MutableLiveData<Location>()

    //保存几个可供切换的地点信息
    val placeOptions= mutableListOf<Place>()

    val weatherLiveData=Transformations.switchMap(locationLiveData){location->
        //看本地有无指定地点的天气信息,如果有，则从本地获取，如果没有，就从网络获取
        if(!Repository.isWeatherExist(location.toString())){
            LogUtil.d("WeatherViewModel.refreshWeather",location.toString())
            //这里开启一个子线程
            val result=Repository.refreshWeather(location.lat,location.lng)
            LogUtil.d("LiveDataTest","startGetValue result:${result.value}")
            if(result.value?.isFailure?:true){
                //如果请求失败就恢复数据
                //需要判断是否存在备份数据
                if(Repository.isWeatherExist("local ${Location(lat,lng)}")){
                    val temp=Repository.getWeather("local ${Location(lat,lng)}")
                    Repository.addWeather(Location(lat,lng).toString(),temp)
                    result
                }else{
                   result
                }
            }else{
                result
            }
        }else{
            LogUtil.d("WeatherViewModel.getWeather",location.toString())
            MutableLiveData<Result<Weather>>(Result.success(Repository.getWeather(Location(location.lat,location.lng).toString())))
        }
        //MutableLiveData<Result<Weather>>(null)
    }

    var lat:Double=0.0

    var lng:Double=0.0

    var placeName=""

    //强制从网络获取天气信息
    fun refreshWeather(){
        //先将当前数据备份一份，防止当请求失败的时候本地数据丢失（如果存在的话）
       if(Repository.isWeatherExist(Location(lat,lng).toString())){
           val temp=Repository.getWeather(Location(lat,lng).toString())
           if(temp!=null){
               Repository.addWeather("local ${Location(lat,lng)}",temp)
           }
       }
        Repository.removeWeather(lat, lng)
        locationLiveData.value= Location(lat,lng)
    }

    //获取天气信息
    fun getWeather(){
        locationLiveData.value= Location(lat,lng)
    }

    //移除指定地点的天气缓存
    fun removeWeather(lat:Double,lng:Double)=Repository.removeWeather(lat, lng)

    //刷新常用地点列表
    fun getPlaceOptions(){
        placeOptions.clear()
        placeOptions.add(Repository.getRestoredPlace())
        for(i in 0 until Repository.getPlaceIndex()){
            placeOptions.add(Repository.getPlaceFromList(i.toString()))
        }
    }

    //从常用地点列表中移除地点
    fun removePlace(key:String){
        Repository.removePlace(key)
        getPlaceOptions()
    }

    fun changePlace(place: Place){
        lat=place.location.lat
        lng=place.location.lng
        placeName=place.name
    }

}